package Lee_code;

import java.math.BigInteger;
import java.time.OffsetDateTime;

/**
 * @author blh
 * @date 2024年06月28日 8:52
 */
public class Lee_8_628 {
    static int myAtoi(String s) {
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        // 正负指示器
        int sign = 1;
        boolean signSign = false;
        boolean signNum = false;
        boolean signSpace = false;
        for (int i = 0; i < len; i++) {
            if (!Character.isDigit(s.charAt(i)) &&
                    s.charAt(i) != ' ' &&
                    s.charAt(i) != '+' &&
                    s.charAt(i) != '-') {
                break;
            }
            if ((signNum && !Character.isDigit(s.charAt(i)))) {
                break;
            }

            if (signSign && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
                break;
            }
            if (signSpace && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
                break;
            }

            if (s.charAt(i) == ' ') {
                signSpace = true;
                continue;
            }
            if (s.charAt(i) == '-') {
                sign = -1;
                signSign = true;
            } else if (s.charAt(i) == '+') {
                sign = 1;
                signSign = true;
            }
            if (Character.isDigit(s.charAt(i))) {
                signNum = true;
                sb.append(s.charAt(i));
            }
        }
        if (sb.length() == 0) {
            return 0;
        }
        BigInteger max = BigInteger.valueOf((long) (Math.pow(2, 31) - 1));
        BigInteger min = BigInteger.valueOf((long) (-Math.pow(2, 31)));

        // 使用bigInteger
        BigInteger res = new BigInteger(sb.toString());
        res = res.multiply(new BigInteger(String.valueOf(sign)));
        if (res.compareTo(max) > 0) {
            return max.intValue();
        }

        if (res.compareTo(min) < 0) {
            return min.intValue();
        }
        return res.intValue();
    }

    public static void main(String[] args) {
        String str = "  +  413";
        myAtoi(str);

    }
}
